<template>
  <!-- 页面主体 -->
  <div class="main">
    <!-- 大标题 -->
    <mine-title>数据集管理</mine-title>
    <!-- 主体内容 -->
    <div class="content">
      <!-- 按钮 -->
      <div class="block-header">
        <div class="block-header-left">
          <mine-button type="primary" @click="addRecord()"
            ><i class="iconfont icon-add-line"></i>新建数据集</mine-button
          >
          <mine-button @click="delRecord()" secondary :disabled="isSelection"
            ><i class="iconfont icon-delete-line"></i>删除</mine-button
          >
          <mine-button type="primary" secondary @click="loadData()"
            ><i class="iconfont icon-reset-line"></i>刷新</mine-button
          >
        </div>
        <div class="block-header-right"></div>
      </div>
      <!-- 表单/表格 -->
      <el-table
        :data="tableData"
        style="width: 100%"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        ref="multipleTable"
      >
        <el-table-column type="selection" width="45"></el-table-column>
        <!-- <el-table-column prop="id" label="数据集ID" show-overflow-tooltip></el-table-column> -->
        <el-table-column label="序号" show-overflow-tooltip width="60">
          <template slot-scope="scope">
            <span>{{ scope.$index + (currentPage - 1) * pageSize + 1 }} </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="fileName"
          label="数据集名称"
          show-overflow-tooltip
        >
          <template slot="header">
            <span>数据集名称</span>
            <mine-table-search
              @searchSubmit="searchSubmit"
              name="fileName"
            ></mine-table-search>
          </template>
        </el-table-column>
        <el-table-column
          prop="fileDesc"
          label="数据集描述"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column prop="fileType" label="类型" show-overflow-tooltip>
          <template slot="header">
            <span>类型</span>
            <mine-table-screen
              @screenSubmit="screenSubmit"
              name="fileType"
              :list="options"
              idKey="name"
              nameKey="text"
            ></mine-table-screen>
          </template>
          <template slot-scope="scope">
            {{
              $common.fetchSingleWord({
                val: scope.row.fileType,
                dict: options,
                idKey: "name",
                nameKey: "text",
              })
            }}
          </template>
        </el-table-column>
        <el-table-column prop="fileSize" label="文件大小" show-overflow-tooltip>
          <template slot-scope="scope">{{
            $common.formatFileSize(scope.row.fileSize, 0)
          }}</template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间"
          :formatter="formatDateTime"
          show-overflow-tooltip
          sortable
        ></el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <mine-button
              size="mini"
              type="text"
              @click="downloadFile(scope.row)"
              :loading="scope.row.loading"
              >下载</mine-button
            >
          </template>
        </el-table-column>
      </el-table>
      <mine-pagination
        @numberChange="numberChange"
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
      >
      </mine-pagination>
    </div>
  </div>
</template>

<script>
import request from "@/modules/index/utils/request";
import { classifyList } from "@/utils/common";
import qs from "qs";
import moment from "moment";
import _ from "lodash";
import { QWebChannel } from "@/modules/index/utils/qwebchannel.js";
export default {
  data() {
    return {
      tableData: [],
      total: 0,
      pageSize: 10,
      currentPage: 1, //table当前页数
      listQuery: {
        id: "",
        fileName: "",
        fileDesc: "",
        fileTypes: [],
        fileSize: "",
        createTime: null,
      },
      loading: false,
      tableHeight: "40%", //table可显示区域高度
      multipleSelection: [],
      options: classifyList,
    };
  },
  mounted() {
    this.loadData();
  },
  methods: {
    async downloadFile(val) {
      this.$set(val, "loading", true);
      try {
        let res = {};
        let _self = this;
        if (_self.$qwebUtil.isQtClient) {
          const uuid = _self.$qwebUtil.generateRandomUUID();
          let sendObject;
          /* eslint-disable-next-line */
          const channel = new QWebChannel(
            window.qt.webChannelTransport,
            async function (channel) {
              sendObject = channel.objects.sendObject;
              // receivedJSON 修改此处发送请求参数
              const receivedJSON = {
                RequestUrl: `/material-info/downloadfile?fileId=${val.id}`,
                RequestMethod: "post",
                ContentType: "application/json;charset=UTF-8",
                RequestBody: {},
                isStringParam: false,
                requestId: uuid,
              };
              await _self.$qwebUtil.receive(sendObject, receivedJSON);
              // console.error('received','/feCanvas/pageList')
              // await send();
            }
          );
          /* eslint-disable-next-line */
          // async function send() {
          //   sendObject.sendMessage.connect(function (data) {
          //     if (!data) {
          //       console.error("No data received.");
          //     }
          //     res = JSON.parse(data);
          //     const result = res.response || {};
          //     // update the followings
          //     if (result.success && res.webInfo.requestId == uuid) {
          //       // _self.$message.success("删除成功");
          //       // _self.loadData(true);
          //     } else {
          //       // _self.$message.error(result.msg || "删除失败");
          //     }
          //   });
          // }
        } else if (this.$webview2.isWPF) {
          const uuid = this.$webview2.generateRandomUUID();
          await this.$webview2.sendWebView2(
            `/material-info/downloadfile?fileId=${val.id}`,
            "post",
            "application/json;charset=UTF-8",
            {},
            false,
            uuid
          );
        } else {
          await this.$store.dispatch("dataAdminMaterialInfoDownloadfile", {
            fileId: val.id,
          });
        }
      } catch (e) {
        console.error(e);
      }
      this.$set(val, "loading", false);
    },
    searchSubmit(value) {
      if (value.key === "fileName") {
        this.listQuery.fileName = value.value;
      }
      this.loadData(true);
    },
    screenSubmit(value) {
      if (value.key === "fileType") {
        this.listQuery.fileTypes = value.value;
      }
      this.loadData(true);
    },
    async loadData(flag) {
      if (flag) {
        this.currentPage = 1;
      }
      const { currentPage, listQuery } = this;
      const { id, fileName, fileDesc, fileTypes, fileSize, createTime } =
        listQuery;
      let date = createTime ? moment(createTime).format("YYYY-MM-DD") : "";

      let data = qs.parse({
        page: currentPage,
        pageSize: this.pageSize,
        id: id,
        fileName: fileName,
        fileDesc: fileDesc,
        fileTypes: fileTypes,
        fileSize: fileSize,
        createTimeFrom: date,
      });
      this.loading = true;
      let res = {};
      let _self = this;
      if (_self.$qwebUtil.isQtClient) {
        const uuid = _self.$qwebUtil.generateRandomUUID();
        let sendObject;
        /* eslint-disable-next-line */
        const channel = new QWebChannel(
          window.qt.webChannelTransport,
          async function (channel) {
            sendObject = channel.objects.sendObject;
            // receivedJSON 修改此处发送请求参数
            const receivedJSON = {
              RequestUrl: "/material-info/search",
              RequestMethod: "post",
              ContentType: "application/json;charset=UTF-8",
              RequestBody: data,
              isStringParam: false,
              requestId: uuid,
            };
            await send();
            await _self.$qwebUtil.receive(sendObject, receivedJSON);
            // console.error('received','/feCanvas/pageList')
          }
        );
        /* eslint-disable-next-line */
        async function send() {
          sendObject.sendMessage.connect(function (data) {
            this.loading = false;
            if (!data) {
              console.error("No data received.");
            }
            res = JSON.parse(data);
            const result = res.response || {};
            _self.loading = false;
            // update the followings
            if (result.success && res.webInfo.requestId == uuid) {
              if (!result.success) {
                return;
              }
              let data = result.data;
              _self.tableData = data.list;
              _self.total = data.rowCount;
            } else {
              _self.$message.error(result.msg || "加载失败");
            }
          });
        }
      } else if (this.$webview2.isWPF) {
        const uuid = this.$webview2.generateRandomUUID();
        await this.$webview2.sendWebView2(
          "/material-info/search",
          "post",
          "application/json;charset=UTF-8",
          data,
          false,
          uuid
        );
        await window.chrome.webview.addEventListener(
          "message",
          (e) => {
            let res = e.data.response;
            if (res.status === 200 && e.data.webInfo.requestId === uuid) {
              if (!res.success) {
                return;
              }
              let data = res.data;
              this.tableData = data.list;
              this.total = data.rowCount;
            } else {
              this.$message.warning("加载失败");
            }
            this.loading = false;
          },
          { once: true }
        );
      } else {
        request({
          url: "/material-info/search", //接口
          method: "post",
          data: data,
        }).then((response) => {
          let result = response.data;
          if (!result.success) {
            return;
          }
          let data = result.data;
          this.tableData = data.list;
          this.total = data.rowCount;
          this.loading = false;
        });
      }
    },
    addRecord() {
      this.$router.push("/dataedit");
    },
    delRecord() {
      this.$mineConfirm("确认要删除这个数据集", "删除提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const ids = this.multipleSelection.map((item) => item.id);
          let res = {};
          let _self = this;
          if (_self.$qwebUtil.isQtClient) {
            const uuid = _self.$qwebUtil.generateRandomUUID();
            let sendObject;
            /* eslint-disable-next-line */
            const channel = new QWebChannel(
              window.qt.webChannelTransport,
              async function (channel) {
                sendObject = channel.objects.sendObject;
                // receivedJSON 修改此处发送请求参数
                const receivedJSON = {
                  RequestUrl: `/material-info/batch${_self.$qwebUtil.convertIdListToQueryString(
                    ids
                  )}`,
                  RequestMethod: "delete",
                  ContentType: "application/json;charset=UTF-8",
                  RequestBody: {},
                  isStringParam: false,
                  requestId: uuid,
                };
                await send();
                await _self.$qwebUtil.receive(sendObject, receivedJSON);
                // console.error('received','/feCanvas/pageList')
              }
            );
            /* eslint-disable-next-line */
            async function send() {
              sendObject.sendMessage.connect(function (data) {
                if (!data) {
                  console.error("No data received.");
                }
                res = JSON.parse(data);
                const result = res.response || {};
                // update the followings
                if (result.success && res.webInfo.requestId == uuid) {
                  _self.page = 1;
                  _self.$message.success("删除成功");
                  _self.loadData();
                } else {
                  _self.$message.error(result.msg || "删除失败");
                }
              });
            }
          } else if (this.$webview2.isWPF) {
            const uuid = this.$webview2.generateRandomUUID();
            await this.$webview2.sendWebView2(
              `/material-info/batch${this.$webview2.convertIdListToQueryString(
                ids
              )}`,
              "delete",
              "application/json;charset=UTF-8",
              {},
              false,
              uuid
            );
            await window.chrome.webview.addEventListener(
              "message",
              (e) => {
                let res = e.data;
                const result = res.response || {};
                if (result.success && res.webInfo.requestId == uuid) {
                  this.page = 1;
                  this.$message.success("删除成功");
                  this.loadData();
                } else {
                  this.$message.error(result.msg || "删除失败");
                }
              },
              {
                once: true,
              }
            );
          } else {
            request({
              url: "/material-info/batch", //接口
              method: "delete",
              params: {
                idList: ids,
              },
              paramsSerializer: (params) => {
                return qs.stringify(params, { indices: false });
              },
            }).then((response) => {
              let result = response.data;
              if (!result.success) {
                this.$message.error("删除失败");
                return;
              }
              this.page = 1;
              this.$message.success("删除成功");
              this.loadData();
            });
          }
        })
        .catch(() => {});
    },
    clear() {
      this.$refs.form.resetFields();
      this.loadData(true);
    },
    refreshData() {
      this.loadData();
    },
    reSetData() {
      this.listQuery = {
        id: "",
        fileName: "",
        fileDesc: "",
        fileTypes: [],
        fileSize: "",
        createTime: null,
      };
      this.page = 1;
      this.refreshData();
    },
    handleSelectionChange(selection) {
      this.multipleSelection = selection;
    },
    handleCurrentChange(value) {
      this.page = value;
      this.loadData();
    },
    formatDateTime(row, column, cellValue, index) {
      let result = moment(cellValue).format("YYYY-MM-DD HH:mm:ss");
      return result;
    },
    renderFileType(value) {
      let result = "";
      result = _.find(this.options, { name: value })
        ? _.find(this.options, { name: value }).text
        : "";
      return result;
    },
    numberChange(val) {
      switch (val.flag) {
        case "pageSize":
          this.pageSize = val.pageSize;
          this.loadData(true);
          break;
        case "currentPage":
          this.currentPage = val.currentPage;
          this.loadData(false);
          break;
        default:
          break;
      }
    },
  },
  computed: {
    isSelection: function () {
      return this.multipleSelection.length === 0;
    },
  },
};
</script>
<style scoped lang="less">
.demo-form-inline {
  margin-bottom: 22px;
  .el-form-item {
    margin-bottom: 0;
  }
  .el-date-editor.el-input,
  .el-date-editor.el-input__inner {
    width: 100%;
  }
}
</style>
